package com.heima.user.service.impl;

import com.heima.common.exception.CustException;
import com.heima.common.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //1.校验参数（是否登录，operation值）
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }
        int operation = dto.getOperation().intValue();
        if (operation != 0 && operation != 1){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请求参数错误");
        }
        Integer loginUserId = user.getId();
        Integer authorUserId = dto.getAuthorApUserId();

        //2.判断operation的值是否为0，代表关注请求
        if (operation == 0){
            Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(authorUserId));
            //2.1校验：不能重复关注
            if (score != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"您已经关注过该作者，请勿重复关注");
            }
            //2.2校验：不能自己关注自己
            if (loginUserId.equals(authorUserId)){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"不能自己关注自己");
            }
            //2.3在当前登录用户的关注集合中，加入作者对应的apUserId
            redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST + loginUserId,
                    String.valueOf(authorUserId),System.currentTimeMillis());
            //2.4在作者对应的粉丝集合中添加登录用户id
            redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST + authorUserId,
                    String.valueOf(loginUserId),System.currentTimeMillis());
        }else {
            //3.判断operation的值是否为1，代表取消关注请求
            //3.1在当前登录用户的关注集合中，删除作者对应的apUserId
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorUserId));
            //3.2在作者对应的粉丝集合中删除登录用户id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + authorUserId, String.valueOf(loginUserId));
        }
        return ResponseResult.okResult();
    }
}
